#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@file database.py
@author weiximei
@date 2025/3/5 14:58
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import SQLAlchemyError

from internal.manager import config_manager

db = SQLAlchemy()


def init_db(app: Flask):
    """
    初始化数据库
    Args:
        app: Flask 应用实例
        database_url: 数据库连接 URL
    """
    if config_manager.config.database:
        database_url = config_manager.config.database.get_connection_url()
        app.config['SQLALCHEMY_DATABASE_URI'] = database_url
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        app.config['SQLALCHEMY_ECHO'] = True  # 开启 SQL 日志
        db.init_app(app)
        # with app.app_context():
        #     # 在应用上下文中测试数据库连接
        #     if not test_db_connection():
        #         raise RuntimeError("数据库连接失败")


def test_db_connection():
    """测试数据库连接"""
    try:
        # 执行简单查询测试连接
        db.session.execute("SELECT 1 FROM DUAL")
        print("数据库连接测试成功")
        return True
    except SQLAlchemyError as e:
        print(f"数据库连接测试失败: {str(e)}")
        return False
